import {observable,action,configure} from 'mobx'

configure({enforceActions:"observed"})      //使用严格模式的mobx,只允许action修改状态，view不能修改（注意这个是mobx@4.x之后的用法）

// 版本号
const __VERSION__ = 2.0
// 将state保存到localstorage---之“存”方法
const saveState = (key,value) => {
	try {
		localStorage.setItem(key, JSON.stringify({
			value:value,
			version:__VERSION__
		}));
	} catch (err) {
		// ...错误处理
	}
};
// 将state保存到localstorage---之“取”方法
const loadState = (key) => {
	try {
		const serializedState = localStorage.getItem(key)
		if (serializedState === null) {
			return null;
		} else {
			let state = JSON.parse(serializedState);
			if (state.version < __VERSION__) {
				return undefined;
			} else {
				return state.value;
			}
		}
	} catch (err) {
		// ...错误处理
		return undefined;
	}
}

class Store {
	@observable themeColor;

	// 初始化store
	constructor() {
    	this.themeColor = loadState('MOBX_themeColor') || 'red';
	}

	@action changeThemeColor(val){
		this.themeColor = val;
		saveState('MOBX_themeColor',val)
	}
}

export default new Store()